<html>
<head>
<meta http-equiv="content-type" content="text-html; charset=utf-8">
<link type="text/css" href="css/cupertino/jquery-ui-1.8.9.custom.css" rel="Stylesheet" />
<link type="text/css" href="css/main.css" rel="Stylesheet" />	
<script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.9.custom.min.js"></script>
<script type="text/javascript" src="js/jquery.qtip-1.0.0-rc3.min.js"></script>
<script type="text/javascript">

function getDateDiff(old_date){
		var now = new Date().getTime();
		var old_time = old_date.getTime();
		//convert to seconds
		now = Math.floor(now/1000);
		old_time = Math.floor(old_time/1000);
		var sec_diff = now - old_time;
		var minute = 60;
		var hour = minute * 60;
		var day = hour * 24;
		var week = day * 7;
		var ret = '';
		if (sec_diff/week > 1) {
			ret += Math.floor(sec_diff/week) + "周";
			sec_diff -= Math.floor(sec_diff/week)*week;
		} 
		if (sec_diff/day > 1) {
			ret += Math.floor(sec_diff/day) + "天";
			sec_diff -= Math.floor(sec_diff/day)*day;
		}
		if (sec_diff/hour > 1) {
			ret += Math.floor(sec_diff/hour) + "小时";
			sec_diff -= Math.floor(sec_diff/hour)*hour;
		}
		if (sec_diff/minute > 1) {
			ret += Math.floor(sec_diff/minute) + "分钟";
			sec_diff -= Math.floor(sec_diff/minute)*minute;
		}		
		if (sec_diff != 0) {
			ret += sec_diff + "秒";
		}
		return ret;
}

var bg = chrome.extension.getBackgroundPage();
var comment_api_url = 'http://api.t.sina.com.cn/statuses/comments_to_me.json';
var mention_api_url = 'http://api.t.sina.com.cn/statuses/mentions.json';
var follower_api_url = 'http://api.t.sina.com.cn/statuses/followers.json';
var dm_api_url = 'http://api.t.sina.com.cn/direct_messages.json';
var users = {};

function onReplyCmt(cid) {
	$('#reply_div_' + cid).slideDown();
}

function onCommentWeibo(weibo_id) {
	$('#comment_div_' + weibo_id).slideDown();
}

function onReplyDm(dm_id) {
	$('#dm_reply_div_' + dm_id).slideDown();
}

function onCancleReply(cid) {
	$('#reply_div_' + cid).slideUp();
}

function onCancleComment(weibo_id) {
	$('#comment_div_' + weibo_id).slideUp();
}

function onCancleDmReply(dm_id) {
	$('#dm_reply_div_' + dm_id).slideUp();
}

function onDeleteReply(reply_id) {
	var delete_reply_api = "http://api.t.sina.com.cn/statuses/comment_destroy/" + reply_id + ".json";
	var request = {
			'method' : 'POST',
			'parameters':{
			}};
	bg.sendRequest(delete_reply_api, function(rsp,xhr) {
						$('#reply_' + reply_id).fadeOut();
					},request);
}

function onDeleteDm(dm_id) {
	var delete_dm_api = "http://api.t.sina.com.cn/direct_messages/destroy/" + dm_id + ".json";
	var request = {
			'method' : 'POST',
			'parameters':{
			}};
	bg.sendRequest(delete_dm_api, function(rsp,xhr) {
						$('#dm_all_' + dm_id).fadeOut();
					},request);
}


function onDeleteComment(comment_id) {
	var delete_comment_api = "http://api.t.sina.com.cn/statuses/comment_destroy/" + comment_id + ".json";
	var request = {
			'method' : 'POST',
			'parameters':{
			}};
	bg.sendRequest(delete_comment_api, function(rsp,xhr) {
						$('#comment_' + comment_id).fadeOut();
					},request);
}

function generateReplyDiv(reply_text,reply_id) {
	var html = "<div class='item' id='reply_" + reply_id + "'>";
	html +=reply_text;
	html += "<br>";
	var now = new Date();
	var sent_time = now.getHours() + "点" + now.getMinutes() + "分";
	html += "<i>已于" + sent_time + "发送成功</i>&nbsp&nbsp";
	html += "<a href='' onclick='onDeleteReply(" + reply_id + ");return false;'>删除</a>";
	html += "</div>"
	return html;
}

function generateCommentDiv(comment_text,comment_id) {
	var html = "<div class='item' id='comment_" + comment_id + "'>";
	html +=comment_text;
	html += "<br>";
	var now = new Date();
	var sent_time = now.getHours() + "点" + now.getMinutes() + "分";
	html += "<i>已于" + sent_time + "发送成功</i>&nbsp&nbsp";
	html += "<a href='' onclick='onDeleteComment(" + comment_id + ");return false;'>删除</a>";
	html += "</div>"
	return html;
}

function generateDmReplyDiv(dm_text,dm_id) {
	var html = "<div class='item' id='dm_reply_" + dm_id + "'>";
	html += dm_text;
	html += "<br>";
	var now = new Date();
	var sent_time = now.getHours() + "点" + now.getMinutes() + "分";
	html += "<i>已于" + sent_time + "发送成功</i>";
	html += "</div>"
	return html;
}

function onSubmitReply(cmt_id,weibo_id) {
	var cmt_reply_api = "http://api.t.sina.com.cn/statuses/reply.json";
	var reply_text = $('#reply_ta_' + cmt_id).val();
	if(reply_text){
		console.log(reply_text);
		var request = {
					'method' : 'POST',
					'parameters':{
						'cid' : cmt_id,
						'id' : weibo_id,
						'comment' : encodeURIComponent(reply_text)
					}};
		bg.sendRequest(cmt_reply_api,function(rsp,xhr){
							//console.log(rsp);
							var ret_obj = eval('(' + rsp + ')');
							var reply_id = ret_obj.id;
							console.log('reply id is ' + reply_id);
							$('#reply_div_' + cmt_id).slideUp();
							//Todo
							// 在reply_show_cid里面增加新的div,使用append
							var reply_html = generateReplyDiv(reply_text,reply_id);
							$('#reply_show_' + cmt_id).append(reply_html);
						}, request);
	}
}

function onSubmitComment(weibo_id) {
	var comment_api = "http://api.t.sina.com.cn/statuses/comment.json";
	var comment_text = $('#comment_ta_' + weibo_id).val();
	if(comment_text){
		console.log(comment_text);
		var request = {
					'method' : 'POST',
					'parameters':{
						'id' : weibo_id,
						'comment' : encodeURIComponent(comment_text)
					}};
		bg.sendRequest(comment_api,function(rsp,xhr){
							//console.log(rsp);
							var ret_obj = eval('(' + rsp + ')');
							var comment_id = ret_obj.id;
							console.log('comment id is ' + comment_id);
							$('#comment_div_' + weibo_id).slideUp();
							// 在reply_show_cid里面增加新的div,使用append
							var comment_html = generateCommentDiv(comment_text,comment_id);
							$('#men_cmt_show_' + weibo_id).append(comment_html);
						}, request);
	}
}

function onSubmitDmReply(dm_id,dm_sender_id) {
	var new_dm_api = "http://api.t.sina.com.cn/direct_messages/new.json";
	var dm_text = $('#dm_ta_' + dm_id).val();
	if(dm_text) {
		console.log(dm_text);
		var request = {
					'method' : 'POST',
					'parameters':{
						'id' : dm_sender_id,
						'text' : encodeURIComponent(dm_text)
					}};
		bg.sendRequest(new_dm_api,function(rsp,xhr){
							//console.log(rsp);
							var ret_obj = eval('(' + rsp + ')');
							var reply_dm_id = ret_obj.id;
							console.log('reply dm id is ' + dm_id);
							$('#dm_reply_div_' + dm_id).slideUp();
							var dm_reply_html = generateDmReplyDiv(dm_text,dm_id);
							$('#dm_reply_show_' + dm_id).append(dm_reply_html);
						}, request);
	} 
}

function generateCmtDiv(cmt_obj){
	var html = "<div class ='frame'>";
	var text = cmt_obj.text;
	var cid = cmt_obj.id;
	var weibo_id = cmt_obj.status.id;
	var username = cmt_obj.user.screen_name;
	var uid = cmt_obj.user.id;
	var cmt_time = cmt_obj.created_at;
	var weibo = cmt_obj.status.text;
	weibo = weibo.substr(0,45);
	if("retweeted_status" in cmt_obj.status && weibo.length < 45) {
		weibo += cmt_obj.status.retweeted_status.text.substr(0,45 - weibo.length);
	}
	weibo += "...";	
	
	var comment_div = "<div><p><a rel='" + uid + "'>" + username + "</a>";
	comment_div += "于" + getDateDiff(new Date(cmt_time)) + "前对";
	comment_div += "<u>“" + weibo +"”</u>";
	comment_div +="评论道:&nbsp“";
	comment_div += "<b>" + text + "</b>";
	comment_div += "”</p></div>";

	html += comment_div;
	
	var reply_show_div = "<div class='item_div_show' id='" + "reply_show_" + cid + "'>";
	reply_show_div += "</div>";
	
	html += reply_show_div;
	
	var reply_div = "<div class='cmt_reply'>";
	reply_div += "<div class='reply_div' id='" + "reply_div_" + cid + "'>";
	reply_div += "<textarea id='" + "reply_ta_" + cid + "' warp='virtual'></textarea>";
	reply_div += "<p><a href='' onclick='onSubmitReply(\"" + cid + "\",\""  + weibo_id + "\");return false;'>确定</a>&nbsp";
	reply_div += "<a href='' onclick='onCancleReply(\"" + cid + "\");return false;'>取消</a></p>";
	reply_div += "</div>";
	reply_div += "<p><a href='' style='margin-left:85%' onclick='onReplyCmt(\"" + cid + "\");return false;'>回复</a></p>";
	reply_div += "</div>";
	html += reply_div;
	
	html += "</div>";
	return html;
}

function generateMenDiv(men_obj){
	var html = "<div class ='frame'>";
	var weibo_id = men_obj.id;
	var username = men_obj.user.screen_name;
	var uid = men_obj.user.id;
	var men_time = men_obj.created_at;
	var weibo = men_obj.text;
	console.log(weibo);
	weibo = weibo.substr(0,45);
	if("retweeted_status" in men_obj && weibo.length < 45) {
		weibo += men_obj.retweeted_status.text.substr(0,45 - weibo.length);
	}
	weibo += "...";	
	
	var mention_div = "<div><p><a rel='" + uid + "'>" + username + "</a>";
	mention_div += "于" + getDateDiff(new Date(men_time)) + "前说道";
	mention_div += "<u>“" + weibo +"”</u>";
	mention_div += "”</p></div>";

	html += mention_div;
	//console.log(html);
	
	var mention_cmt_show_div = "<div class='item_div_show' id='" + "men_cmt_show_" + weibo_id + "'>";
	mention_cmt_show_div += "</div>";
	
	html += mention_cmt_show_div;
	
	var comment_div = "<div class='cmt_reply'>";
	comment_div += "<div class='comment_div' id='" + "comment_div_" + weibo_id + "'>";
	comment_div += "<textarea id='" + "comment_ta_" + weibo_id + "' warp='virtual'></textarea>";
	comment_div += "<p><a href='' onclick='onSubmitComment(\"" + weibo_id + "\");return false;'>确定</a>&nbsp";
	comment_div += "<a href='' onclick='onCancleComment(\"" + weibo_id + "\");return false;'>取消</a></p>";
	comment_div += "</div>";
	comment_div += "<p><a href='' style='margin-left:85%' onclick='onCommentWeibo(\"" + weibo_id + "\");return false;'>回复</a></p>";
	comment_div += "</div>";
	html += comment_div;
	
	html += "</div>";
	return html;
}


function followUser(ele,uid) {
	console.log("followUser");
	var follow_api = "http://api.t.sina.com.cn/friendships/create.json";
	var request = {
			'method' : 'POST',
			'parameters':{
				'user_id' : uid,
			}};
	bg.sendRequest(follow_api,function(rsp,xhr){
						ele.firstChild.data = "已关注,取消关注";
					}, request);
}

function unfollowUser(ele,uid) {
	console.log("unfollowUser");
	var unfollow_api = "http://api.t.sina.com.cn/friendships/destroy.json";
	var request = {
			'method' : 'POST',
			'parameters':{
				'user_id' : uid,
			}};
	bg.sendRequest(unfollow_api,function(rsp,xhr){
						ele.firstChild.data = "已取消关注，加关注";
					}, request);
}

function doFollow(ele,id){
	var follow_status_api = "http://api.t.sina.com.cn/friendships/show.json";
	//console.log(ele.firstChild.data);
	//ele.firstChild.data = "点了";
	var request = {
				'method' : 'GET',
				'parameters':{
					'target_id' : id,
				}};
	bg.sendRequest(follow_status_api, function(rsp,xhr){
					var ret_obj = eval('(' + rsp + ')');
					//if(eval(ret_obj.target.following))
					//console.log(ret_obj);
					//console.log(ret_obj.target.following);
					if(eval(ret_obj.target.followed_by)){
						unfollowUser(ele,id);
					} else {
						followUser(ele,id);
					} 
				},
	request);
	
}

function generateFollowerDiv(follower) {
	var uid = follower.id;
	var profile_img = follower.profile_image_url;
	var followers = follower.followers_count;
	var friends = follower.friends_count;
	var weibos = follower.statuses_count;
	var following = follower.following;
	var verified = follower.verified;
	var desc = follower.description;
	//console.log(followers + ' ' + friends + ' ' + weibos + ' ' + following + ' ' + verified + ' ' + desc);
	
	var html = '<div class="frame">';
	html += "<img src='" + profile_img + "' style='float:left;margin-right:10px;'>";
	html += "<p>" + desc + "</p>";
	//html += "<br>";
	html += "<p>关注" + friends + "人，" + followers + "位粉丝，已发表" + weibos + "篇微博</p>";
	if(verified) {
		html += "新浪认证用户";
	} else {
		html += "未认证用户";
	}
	html += " <a class='follow_link' onclick='doFollow(this," + uid + ")'>";
	if(following) {
		html += "已关注，取消关注";
	} else {
		html += "未关注，加关注";
	}
	html += '</a>';
	html += '</div>';
	console.log(html);
	return html;
}
function generateDmDiv(dm) {
    var dm_time = dm.created_at;
	var dm_id = dm.id;
	var dm_sender_id = dm.sender_id;
	var dm_sender_name = dm.sender_screen_name;
	var receiver = dm.recipient;
	var dm_text = dm.text;
	var html = "<div class ='frame' id = 'dm_all_" + dm_id + "'>";
	var dm_div = "<div><p><a rel='" + dm_sender_id + "'>" + dm_sender_name + "</a>";
	dm_div += "于" + getDateDiff(new Date(dm_time)) + "前发私信说道:";
	dm_div += "<u>“" + dm_text +"”</u>";
	dm_div += "”</p></div>";
	
	html += dm_div;
	
	var dm_reply_show_div = "<div class='item_div_show' id='" + "dm_reply_show_" + dm_id + "'>";
	dm_reply_show_div += "</div>";
	
	html += dm_reply_show_div;
	
	var dm_reply_div = "<div class='cmt_reply'>";
	dm_reply_div += "<div class='dm_reply_div' id='" + "dm_reply_div_" + dm_id + "'>";
	dm_reply_div += "<textarea id='" + "dm_ta_" + dm_id + "' warp='virtual'></textarea>";
	dm_reply_div += "<p><a href='' onclick='onSubmitDmReply(\"" + dm_id + "\",\"" + dm_sender_id + "\");return false;'>确定</a>&nbsp";
	dm_reply_div += "<a href='' onclick='onCancleDmReply(\"" + dm_id + "\");return false;'>取消</a></p>";
	dm_reply_div += "</div>";
	dm_reply_div += "<p><a href='' style='margin-left:75%' onclick='onReplyDm(\"" + dm_id + "\");return false;'>回复</a>";
	dm_reply_div += "&nbsp<a href='' onclick='onDeleteDm(\"" + dm_id + "\");return false;'>删除</a></p>";
	dm_reply_div += "</div>";
	html += dm_reply_div;
	html += "</div>";
	return html;
	
}

function generateUserPopUpDiv(uid) {
	console.log('xxx');
	var profile_img = users[uid].profile_image_url;
	var followers = users[uid].followers_count;
	var friends = users[uid].friends_count;
	var weibos = users[uid].statuses_count;
	var following = users[uid].following;
	var verified = users[uid].verified;
	var desc = users[uid].description;
	//console.log(followers + ' ' + friends + ' ' + weibos + ' ' + following + ' ' + verified + ' ' + desc);
	
	var html = '<div>';
	html += "<img src='" + profile_img + "' style='float:left;margin-right:10px;'>";
	html += "<p>" + desc + "</p>";
	//html += "<br>";
	html += "<p>关注" + friends + "人，" + followers + "位粉丝，已发表" + weibos + "篇微博</p>";
	if(verified) {
		html += "新浪认证用户";
	} else {
		html += "未认证用户";
	}
	html += " <a class='follow_link' onclick='doFollow(this," + uid + ")'>";
	if(following) {
		html += "已关注，取消关注";
	} else {
		html += "未关注，加关注";
	}
	html += '</a>';
	html += '</div>';
	console.log(html);
	return html;

}

function addUserToolTip() {
	$('a[rel]').each(function(){
		var user_html = generateUserPopUpDiv($(this).attr('rel'));
		$(this).qtip(
		  {
			 content: {
				// Set the text to an image HTML string with the correct src URL to the loading image you want to use
				//text: '<img src="' + cmt_users[$(this).attr('rel')].profile_image_url + '"/>',
				text: user_html,
				title: {
				   text: ' ' + $(this).text(), // Give the tooltip a title using each elements text
				   button: 'x' // Show a close link in the title
				}
			 },
			 position: {
				corner: {
				   target: 'bottomMiddle', // Position the tooltip above the link
				   tooltip: 'topMiddle'
				},
				adjust: {
				   screen: true // Keep the tooltip on-screen at all times
				}
			 },
			 show: { 
				//when: 'click', 
				when: {target: false},
				solo: true // Only show one tooltip at a time
			 },
			 hide: 'unfocus',
			 style: {
				tip: true, // Apply a speech bubble tip to the tooltip at the designated tooltip corner
				border: {
				   width: 0,
				   radius: 4
				},
				name: 'blue', // Use the default light style
				//width: 50 // Set the tooltip width
			 }
		  })
});
}

$(function(){
	$( "#tabs" ).tabs();
	console.log($( "#tabs" ).tabs("widget"));
	var str = '';
	var cmt_flag = localStorage.getItem('tc_comment_flag');
	var fol_flag = localStorage.getItem('tc_follower_flag');
	var dm_flag = localStorage.getItem('tc_dm_flag');
	var men_flag = localStorage.getItem('tc_mention_flag');
	var cmt_num = fol_num = dm_num = men_num = 0;
	if(eval(cmt_flag)){
		cmt_num = localStorage.getItem('tc_comments');
		if(cmt_num > 0) { 
			var request = {
				'method' : 'GET',
				'parameters':{
					'page' : 1,
					'count' : cmt_num
				}};
			bg.sendRequest(comment_api_url,function(rsp,xhr){
				var ret_obj = eval('(' + rsp + ')');
				//console.log(typeof(ret_obj));
				var cmt_html = '';
				for ( var idx in ret_obj ) {
					users[ret_obj[idx].user.id] = ret_obj[idx].user;
					cmt_html += generateCmtDiv(ret_obj[idx]);
				}
				$("#tabs-cmts").html(cmt_html);
				//用户名qtip
				addUserToolTip();
			},request);
			
		} else {
			// Remove the tab
			$('#tabs').tabs("remove",0);
		}
	} 
	if(eval(fol_flag)){
		fol_num = localStorage.getItem('tc_followers');
		if(fol_num > 0) {
			var request = {
				'method' : 'GET',
				'parameters':{
					'cursor' : -1,
					'count' : fol_num
				}};
			bg.sendRequest(follower_api_url,function(rsp,xhr){
				var ret_obj = eval('(' + rsp + ')');
				var follower_list = ret_obj['users'];
				console.log(follower_list);
				var follower_html = '';
				for (var idx in follower_list) {
					console.log(follower_list[idx]);
					follower_html += generateFollowerDiv(follower_list[idx]);
				}
				$("#tabs-fans").html(follower_html);
			}, request);
		} else {
			$('#tabs').tabs("remove",$('#tabs').tabs("length") - 3);
		}
	} 
	if(eval(dm_flag)){
		dm_num = localStorage.getItem('tc_dm');
		if(dm_num > 0) { 
			var request = {
				'method' : 'GET',
				'parameters':{
					'count' : dm_num
				}};
			bg.sendRequest(dm_api_url,function(rsp,xhr){
				var ret_obj = eval('(' + rsp + ')');
				var dm_list = ret_obj;
				var dm_html = '';
				for (var idx in dm_list) {
					console.log(dm_list[idx]);
					users[dm_list[idx].sender.id] = dm_list[idx].sender;
					dm_html += generateDmDiv(dm_list[idx]);
				}
				$("#tabs-dms").html(dm_html);
				addUserToolTip();
			}, request);
		} else {
			$('#tabs').tabs("remove",$('#tabs').tabs("length") - 2);
		}
	}
	if(eval(men_flag)){
		men_num = localStorage.getItem('tc_mentions');
		if(men_num > 0) { 
			var request = {
				'method' : 'GET',
				'parameters':{
					'page' : 1,
					'count' : men_num
				}};
			bg.sendRequest(mention_api_url,function(rsp,xhr){
				var ret_obj = eval('(' + rsp + ')');
				console.log(ret_obj);
				var men_html = '';
				for ( var idx in ret_obj ) {
					users[ret_obj[idx].user.id] = ret_obj[idx].user;
					men_html += generateMenDiv(ret_obj[idx]);
				}
				$("#tabs-atme").html(men_html);
				//用户名qtip
				addUserToolTip();
			},request);
		} else {
			$('#tabs').tabs("remove",$('#tabs').tabs("length") - 1);
		}
		
	}

})
</script>
<style type="text/css">
body{ font: 62.5% "Trebuchet MS", sans-serif;  
	background: -webkit-gradient(
		linear,
		left top, 
		left bottom, 
		from(#DDF3F7), 
		to(#FFFFFF));
		}
</style>	
</head>
<div id="tabs">
	<ul>
		<li><a href="#tabs-cmts">新评论</a></li>
		<li><a href="#tabs-fans">新粉丝</a></li>
		<li><a href="#tabs-dms">新私信</a></li>
		<li><a href="#tabs-atme">新@我</a></li>
	</ul>
	<div id="tabs-cmts">
	</div>

	<div id="tabs-fans">

	</div>
	<div id="tabs-dms">
	</div>
	<div id="tabs-atme">
		
	</div>
</div>
</html>